/*
 * Copyright 2010 www.LongNet.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using LongNet.Web.Context;
using LongNet.Web.Mvc.Utils;

namespace LongNet.Web.Mvc.Processors {

    internal class NsLayoutProcessor : ProcessorBase {

        public override void Process( ProcessContext context ) {

            MvcEventPublisher.Instance.BeginAddNsLayout( context.ctx );

            MvcContext ctx = context.ctx;

            String content = context.getContent();

            IList paths = ctx.utils.getLayoutPath();
            for (int i = 0; i < paths.Count; i++) {
                content = addLayoutPrivate( paths[i].ToString(), content, ctx );
                if (ctx.utils.isEnd()) {

                    context.endMsgByView( content );
                    return;

                }
            }

            context.setContent( content );
        }

        // path => Blog.Admin
        // path => Blog
        // path => ""
        private static String addLayoutPrivate( String path, String actionContent, MvcContext ctx ) {

            ControllerBase controller = ControllerFactory.FindLayoutController( path, ctx );
            if (controller == null) return actionContent;

            ctx.controller.utils.addHidedLayouts( controller );
            if (ctx.controller.utils.isHided( controller.GetType() )) return actionContent;

            controller.utils.switchViewToLayout();

            ActionRunner.runLayoutAction( ctx, controller, controller.Layout );

            if (ctx.utils.isEnd()) {
                return controller.utils.getActionResult();
            }

            return HtmlCombiner.combinePage( controller.utils.getActionResult(), actionContent );
        }


    }

}
